<?php
namespace app\console\controller;
use app\model\Category as SelfModel;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\facade\Route;
use think\facade\View;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Cookie;
class Category extends Base
{



    public function initialize()
    {
        parent::initialize();
        $this->model = "\app\model\Category";
        $this->list_rows = 20;
        $this->order = ['sort'=>'asc','id'=>'desc'];
    }

    public function select()
    {

    }

    public function index()
    {
        $param = $this->request->param();
        $parent_id = $this->request->param('parent_id',0);
        $where= [['parent_id','=',$parent_id]];
        $data = $this->model::withSearch(array_keys($param),$param)
            ->where($where)
            ->order($this->order)
            ->paginate(['query' => $param,'list_rows'=>$this->list_rows])
            ->each(function ($item,$key){
        });
        $this->select();
        $parent2id = $this->model::where('id',$parent_id)->value('parent_id');
        return View::fetch('', ['data' => $data,'parent2id'=>$parent2id]);
    }

    public function create()
    {

        if ($this->request->isPost()) {
            $param = $this->request->param();
            $lev = $this->model::where('id',$param['parent_id'] ?? 0)->value('level');
            if($lev == 0 || $lev == null){$param['level'] = 1;}
            if($lev == 1){$param['level'] = 2;}
            if($lev == 2){$param['level'] = 3;}
            if($lev == 3){$param['level'] = 4;}
            if($lev == 4){$param['level'] = 5;}
            if($lev >=5){
                fail('最大5级');
            }
            $ret = $this->model::create($param);
            if ($ret) {
                win('操作成功', Route::buildUrl('index'));
            }
            fail('操作失败');
        }
        $this->select();
        return View::fetch('', ['info' => []]);
    }



}